# -*- coding: utf-8 -*-
#
#
##
class ApiController < ApplicationController
#    skip_before_filter :verify_authenticity_token
	#=== 初期化API 
	#
	def init
		rp = Hash.new
		rp['result'] = {}
		begin
			
		rescue 
			rp['result'] = BKH_STATUS_ERROR
			logger.error($!.message)
			logger.error($!.backtrace[0 .. 10].join("\n"))
		end	
		respond_to do |type|
			type.json  { render :text=> rp.to_json }
		end
	end


	#=== ユーザー登録API 
	#
	def user
		rp = Hash.new
		rp['result'] = {}

		begin
			usr = User.create

			rp['data'] = {'user'=>{'id'=>usr.id , 'created_at'=>usr.created_at.iso8601 }}
			rp['result'] = BKH_STATUS_SUCCESS 
		rescue 
			rp['result'] = BKH_STATUS_ERROR
			logger.error($!.message)
			logger.error($!.backtrace[0 .. 10].join("\n"))
		end	
		respond_to do |type|
			type.json  { render :text=> rp.to_json }
		end
	end



	#=== 鉢情報取得API 
	#
	def potlist
		rp = Hash.new
		rp['result'] = {}

		begin
			dt ={}
			userid = params[:userid].to_i

			##パラメーターの形式チェック
			raise ParameterException, "User id is invalid : #{userid}" unless userid > 0

			usr = User.find(userid)
			dt['user'] = {'id'=>usr.id , 'created_at'=>usr.created_at.iso8601}
			pl = []

			usr.getPots().each(){|potid,pitem|
				item = pitem['item_num'].to_i
				special = pitem['special_num'].to_i
				complete = pitem['complete_pattern'].to_i
				imgurl = buildImageUrl(potid, item, complete, special)
				weburl = buildWebPageUrl(userid,potid)
				pl[potid - 1]= {'id'=>potid,'item_num'=>item,'special_num'=>special,'img_url'=>imgurl,'web_url'=>weburl};
			}
			dt['potlist'] = pl

			rp['data'] = dt
			rp['result'] = BKH_STATUS_SUCCESS 

		rescue 
			rp['result'] = BKH_STATUS_ERROR
			logger.error($!.message)
			logger.error($!.backtrace[0 .. 10].join("\n"))
		end	
		respond_to do |type|
			type.json  { render :text=> rp.to_json }
		end
	end



	#=== アイテムリスト取得API 
	#
	def itemlist
		rp = Hash.new
		rp['result'] = {}

		begin
			dt ={}
			userid = params[:userid].to_i 
			potid = params[:potid].to_i
			##パラメーターの形式チェック
			raise ParameterException, "User id is invalid : #{userid}" unless userid > 0
			raise ParameterException, "Pot id is invalid : #{potid}" unless potid > 0 and potid < 6

			usr = User.find(userid)
			dt['user'] = {'id'=>usr.id , 'created_at'=>usr.created_at.iso8601}
			
			po = usr.getPots()
			if po[potid] then
				pt = po[potid]
				item = pt['item_num']
				special = pt['special_num']
				complete = pt['complete_pattern'].to_i
				imgurl = buildImageUrl(potid, item,complete, special)
				weburl = buildWebPageUrl(userid,potid)
				dt['pot'] = {'id'=>potid,'item_num'=>item,'special_num'=>special,'img_url'=>imgurl,'web_url'=>weburl}
			end


			pl = []
			pi = [] ## 楽天ITEM用リスト
			phash = {}  ##一時格納ハッシュ
			Potitem.find(:all, :conditions=>[ "userid=? AND potid=?", userid,potid]).each(){|pti|
				phash.store(pti.barcode,
					{'id'=>pti.id ,
					'barcode'=>pti.barcode,
					'special'=>pti.special,
					'created_at'=>pti.created_at.iso8601
					})
				pi.push pti.barcode
			}
			Rakutenitem.find(:all, :conditions=>[ "barcode IN (?)", pi ]).each(){|ritem|
				barcode = ritem['barcode']
				pri = phash[barcode]
				pri.store('itemname',ritem.itemname)
				pri.store('weburl',ritem.weburl)
				pri.store('imageurl',ritem.imageurl)
				pl.push pri.dup
			}


			dt['potlist'] = pl
			rp['data'] = dt
			rp['result'] = BKH_STATUS_SUCCESS 

		rescue 
			rp['result'] = BKH_STATUS_ERROR
			logger.error($!.message)
			logger.error($!.backtrace[0 .. 10].join("\n"))
		end	
		respond_to do |type|
			type.json  { render :text=> rp.to_json }
		end
	end

	#
	#=== バーコード登録API 
	#
	def barcode
		rp = Hash.new
		rp['result'] = {}


		begin
			userid = params[:userid].to_i
			barcode = params[:barcode]
			
			##パラメーターの形式チェック
			raise ParameterException, "User id is invalid : #{userid}" unless userid > 0
			raise ParameterException ,"Barcode is invalid : #{barcode} "  unless /([0-9]+)/ =~ barcode
			usr = User.find(userid) 

			raise ParameterException, "User parameter is invalid : #{userid}" unless usr
			user_created_at = usr.created_at.iso8601

			## 既に取得しているアイテムかどうか？
			pret = Potitem.find(:first, :conditions=>[ "userid=? AND barcode=?", userid,barcode])
			raise BarcodeRegisteredException , "Barcode is already registered : #{userid} / #{barcode}" if  pret  
			
			##追加アイテムの検索
			tim = {}
			Rakutenitem.transaction{
				## キャッシュに含まれているアイテムかどうか？
				ritm = Rakutenitem.find(:first, :conditions=>[ "barcode=?", barcode ])
				if ritm
					potid = ritm.potid
					rootgenreid = ritm.rootgenreid
					itemname = ritm.itemname
					special = GenreSearch.isSpecial(rootgenreid)
					tim = {'barcode'=>barcode,'potid'=>potid , 'special'=>special , 'name'=>itemname}
				## 新規での楽天APIへの問合せ
				else
					is = ItemSearch.new
					irt = ItemSearch.new.getItemInfo(barcode)

					##ーコードに対応する商品が見つからない場合
					raise BarcodeMissingException , "Barcode was not found in rakuten market : #{barcode} " unless irt  ##

					##楽天アイテムキャッシュへの追加
					rim = Rakutenitem.new
					rim.setRakutenItem(irt)
					rim.save!
					tim = {'barcode'=>barcode,'potid'=>irt[:potid] , 'special'=>irt[:special] , 'name'=>irt[:itemName] }
				end
			}


			##鉢数の更新
			Potitem.transaction{
				pilist = Potitem.find(:all, :conditions=>[ "userid=? ", userid])
				pilist = {} unless pilist
				porl = Potitem.culcPots(pilist)
				potid = tim['potid'].to_i
				special = tim['special'].to_i
				ponum = porl[potid]['item'].to_i 

				##鉢がいっぱいの場合
				raise BarcodeCompletedException , "The pot is full : #{userid} , #{potid} , #{ponum} " if ponum >= BKH_ITEM_LIMIT  ## The pot is full

				##ポットアイテムへの追加
				npi = Potitem.new
				npi.userid = userid
				npi.potid = potid
				npi.barcode = barcode
				npi.special = special
				npi.save!

				##ユーザー鉢数計算の更新
				usr = User.find(userid)
				upo = usr.getPots()
				pilist = Potitem.find(:all, :conditions=>[ "userid=? ", userid])
				porl = Potitem.culcPots(pilist)
				usr.setPots(porl)
				##コンプリート時
				usr.setConplete(potid) if usr.checkComplete(potid) 
				usr.save!
			}

			#結果の格納
			dt = {}
			usr = User.find(userid)
			dt['user'] = {'id'=>usr.id , 'created_at'=>usr.created_at.iso8601}
			
			## 現時点のアイテム状況の取得
			##pti = Potitem.find(:all, :conditions=>[ "userid=?", userid])
			pl = []
			usr.getPots().each(){|potid,pitem|
				item = pitem['item_num'].to_i
				special = pitem['special_num'].to_i
				complete = pitem['complete_pattern'].to_i
				imgurl = buildImageUrl(potid, item, complete, special)
				weburl = buildWebPageUrl(userid,potid)
				pl[potid - 1]= {'id'=>potid,'item_num'=>item,'special_num'=>special,'img_url'=>imgurl,'web_url'=>weburl};
			}
			dt['item'] = tim
			dt['potlist'] = pl

			rp['data'] = dt
			rp['result'] = BKH_STATUS_SUCCESS 

		rescue BarcodeRegisteredException => bre
			##2  100  失敗   registered  既にこのユーザーに対して同じバーコードの商品が登録されています
			rp['result'] = BKH_STATUS_REGISTED
		rescue BarcodeMissingException => bme
			##3  101  失敗  missing  このバーコードに対応する商品が見つかりませんでした
			rp['result'] = BKH_STATUS_MISSING
		rescue BarcodeCompletedException => bce
			#4  102  失敗  completed  このバーコードに対応する鉢は既に完成しています
			rp['result'] = BKH_STATUS_COMPLETED
		rescue Exception => e
			rp['result'] = BKH_STATUS_ERROR
			logger.error($!.message)
			logger.error($!.backtrace[0 .. 10].join("\n"))
		end	
		headers["Content-Type"] = 'text/javascript;'
		render :text=> rp.to_json 
	end



	#=== 画像URL生成
	#
	def buildImageUrl(potid, item, complete, special)
		return sprintf(BKH_IMAGE_URL, potid, item, complete,special)
	end

	#=== ランディングページURL生成
	#
	def buildWebPageUrl(userid,potid)
		return sprintf(BKH_WEB_PAGE_URL,userid, potid)
	end


end




